package org.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.example.api.UserFeignClient;
import org.example.domain.OrderDomain;
import org.example.domain.UserDomain;
import org.example.mapper.OrderMapper;
import org.example.model.Order;
import org.example.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public OrderDomain getOrderById(Long id) {
        Order order = baseMapper.selectById(id);
        if (order != null) {
            OrderDomain orderDomain = new OrderDomain();
            BeanUtils.copyProperties(order, orderDomain);
            if (Objects.nonNull(order.getUserId())) {
                UserDomain userDomain = userFeignClient.getUserById(order.getUserId());
                orderDomain.setUser(userDomain);
            }
            return orderDomain;
        }
        return null;
    }

    @Override
    @GlobalTransactional
    public void createOrder(OrderDomain order) {
        Order order1 = new Order();
        BeanUtils.copyProperties(order, order1);
        baseMapper.insert(order1);
        userFeignClient.insertUser(order.getUserId(),order.getUser());
        throw new RuntimeException("测试回滚");
    }
}
